package com.dcivision.alert.web;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.alert.bean.UpdateAlertLogAction;
import com.dcivision.alert.bean.UpdateAlertSystemLog;
import com.dcivision.alert.core.AlertManager;
import com.dcivision.alert.core.MessageFormatter;
import com.dcivision.alert.core.MessageFormatterFactory;
import com.dcivision.alert.core.MessageInfoBean;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.taglib.channel.FilterUtility;
import com.dcivision.framework.web.AbstractListAction;

public class ListSystemMessageAction extends AbstractListAction {

  public ListSystemMessageAction() {
    this.setListName("messageList");
  }

  public String getFunctionCode() {
    return SystemFunctionConstant.MESSAGE_INBOX;
  }

  public String getMajorDAOClassName() {
    return null;
  }

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
      throws ServletException {
    request.setAttribute(GlobalConstant.FUNCTION_CODE_KEY, "MSG_INBOX");
    Connection conn = (Connection) request.getAttribute(GlobalConstant.DB_KEY);
    SessionContainer sessionContainer = this.getSessionContainer(request);
    ListSystemMessageForm messageform = (ListSystemMessageForm) form;

    retrieveFunctionCode(request, response, mapping);

    List result = new ArrayList();
    String filterItem = messageform.getFilter();
    messageform.setDisableActionType("");
    String readType = messageform.getReadType();
    String[] sysLogIDs = request.getParameterValues("basicSelectedID");

    AlertManager alertManager = new AlertManager(sessionContainer, conn);
    Integer systemLogID = null;
    if (!Utility.isEmpty(sysLogIDs) && sysLogIDs.length > 0) {
      for (int i = 0; i < sysLogIDs.length; i++) {
        if (!Utility.isEmpty(sysLogIDs[i])) {
          systemLogID = TextUtility.parseIntegerObj(sysLogIDs[i]);
        }
        if (null != readType && readType.equals("delete")) {
          alertManager.createSystemLogAction(systemLogID, UpdateAlertLogAction.DELETE_ACTION, null);
        } else {
          if (alertManager.checkForSystemLogActionByActionType(systemLogID, UpdateAlertLogAction.READ_ACTION)) {
            if (null != readType && readType.equals("unRead")) {
              alertManager.deleteLogActionBySystemLogIDCurActor(systemLogID);
            }
          } else {
            if (null != readType && readType.equals("read")) {
              alertManager.createSystemLogAction(systemLogID, UpdateAlertLogAction.READ_ACTION, null);
            }
          }
        }
        try {
          conn.commit();
        } catch (Exception e) {

        }
      }
    }
    if (!Utility.isEmpty(filterItem) && !"-".equals(filterItem)) {
      messageform.setSpecifyActionType(FilterUtility.getSystemMsgObjectTypesAndActionTypes(filterItem));
    } else {
      messageform.setSpecifyActionType(null);
    }

    result = composeMessageList(request, sessionContainer, messageform, alertManager);

    request.setAttribute("messageList", result);
    try {
      this.commit(request);
    } catch (Exception e) {
      log.error(e, e);
    }
    return mapping.findForward("L");
  }

  protected Integer getDocumentObjectID(UpdateAlertSystemLog updateAlertSystemLog) {

    Integer objectID = null;
    String objectType = updateAlertSystemLog.getObjectType().trim();
    
    boolean isDms = (UpdateAlert.DOCUMENT_TYPE.equals(objectType))
    || (UpdateAlert.AUTOMATE_CHECKIN.equals(objectType))
    || (UpdateAlert.ISSUE_TYPE.equals(objectType));
    
    if (isDms) {
      if(Utility.isEmpty(updateAlertSystemLog.getRefObjectID())
          ||UpdateAlert.DOCUMENT_INVITATION_CANCEL.equals(updateAlertSystemLog.getActionType())
          ||UpdateAlert.DOCUMENT_INVITATION_EXPIRED.equals(updateAlertSystemLog.getActionType())
          ||UpdateAlert.DOCUMENT_INVITATION_UPDATE_DUEDATE.equals(updateAlertSystemLog.getActionType())){
        objectID = updateAlertSystemLog.getObjectID();
          }else{
            objectID = updateAlertSystemLog.getRefObjectID();
          }
    }
    return objectID;
  }

  private List composeMessageList(HttpServletRequest request, SessionContainer sessionContainer, ListSystemMessageForm messgeForm,
      AlertManager alertManager) throws ApplicationException {
    List result;
    result = alertManager.getSystemLogListByUserRecordID(sessionContainer.getUserRecordID(), messgeForm, "yes");
    List messageList = new ArrayList();
    MessageFormatter messageFormatter;
    List messageResult = new ArrayList();
    if (result != null) {
      UpdateAlertSystemLog systemLog;
      String style = "";
      java.sql.Timestamp receiveDate = null;
      String sender = "";
      String subject = "";
      String isRead = "";
      String subjectWithLink = "";

      boolean isRight = true;

      Connection dbConn = (Connection) request.getAttribute(GlobalConstant.DB_KEY);
      MessageFormatterFactory messageFormatterFactory = MessageFormatterFactory.getInstance();
      for (int i = 0; i < result.size(); i++) {

        systemLog = (UpdateAlertSystemLog) result.get(i);

        messageFormatter = messageFormatterFactory.getMessageFormatter(systemLog, sessionContainer, dbConn);
        if (messageFormatter != null) {
          isRead = messageFormatter.isRead();
          sender = messageFormatter.getSender();
          subject = messageFormatter.getSubjectWithoutLink();
          messageFormatter.setList(true);
          subjectWithLink = messageFormatter.getSubject();
        } else {
          log.error("MessageFormatter is null, systemLog=" + systemLog);
        }

        style = "no".equals(isRead) ? " style=' font:bold ' " : " ";
        receiveDate = systemLog.getCreateDate();

        isRight = this.filter(sender, subject, isRead, messgeForm);

        if (!isRight) {
          continue;
        }

        MessageInfoBean messageBean = new MessageInfoBean();
        messageBean.setSystemLogID(systemLog.getID().toString());
        messageBean.setSender(sender);
        messageBean.setSubject(subject);
        messageBean.setBoldFont(style);
        messageBean.setArrivalDate(receiveDate);
        messageBean.setSubjectWithLink(subjectWithLink);
        if (!Utility.isEmpty(getDocumentObjectID(systemLog))) {
          messageBean.setDocumentID(String.valueOf(getDocumentObjectID(systemLog)));
        }
        messageBean.setDetail(systemLog.getActionType());

        messageList.add(messageBean);
      }

      sort(messgeForm, messageList);
    }
    if (null != messageList) {
      int count = messageList.size();
      int preNum = 1;
      boolean nxtPageAvailable = false;
      int startNum = TextUtility.parseInteger(messgeForm.getCurStartRowNo());
      int pageSize = TextUtility.parseInteger(messgeForm.getPageOffset());
      int startNum2 = TextUtility.parseInteger(messgeForm.getCurStartRowNo());
      if (startNum2 > count && startNum2 > pageSize) {
        startNum -= pageSize;
        startNum2 -= pageSize;
      }
      for (int i = startNum; i <= messageList.size() && i < (startNum2 + pageSize); i++) {
        MessageInfoBean messageBean = (MessageInfoBean) messageList.get(i - 1);
        messageBean.setRecordCount(count);
        messageBean.setRowNum(startNum++);
        messageBean.setNxtPageAvailable(nxtPageAvailable);
        messageBean.setNxtPageRowNum(startNum + 1);
        messageBean.setPrvPageRowNum(preNum);
        messageResult.add(messageBean);
      }
    }
    return messageResult;
  }

  private boolean isSearch(ListSystemMessageForm messgeForm) {
    boolean isSearch = false;
    isSearch = !(Utility.isEmpty(messgeForm.getSearchReadType()) && Utility.isEmpty(messgeForm.getSearchSubject())
        && Utility.isEmpty(messgeForm.getSearchSender()) && (Utility.isEmpty(messgeForm.getFilter()) || "-".equals(messgeForm.getFilter())));
    return isSearch;
  }

  private void sort(ListSystemMessageForm messgeForm, List messageList) {
    if (messageList != null && messgeForm.isSortable()) {

      final String sortAttr = messgeForm.getSortAttribute();
      final String sortOrder = messgeForm.getSortOrder();

      if (!(sortAttr.equalsIgnoreCase("A.CREATE_DATE") || sortAttr.equalsIgnoreCase("UPDATE_DATE"))) {
        Collections.sort(messageList, new Comparator() {
          public int compare(Object obj1, Object obj2) {
            MessageInfoBean messageBean1 = (MessageInfoBean) obj1;
            MessageInfoBean messageBean2 = (MessageInfoBean) obj2;
            int flag = 0;
            if (sortAttr.equalsIgnoreCase("T.ALERT_SUBJECT")) {
              flag = messageBean1.getSubject().toLowerCase().compareTo(messageBean2.getSubject().toLowerCase());
            }
            if (sortAttr.equalsIgnoreCase("A.CREATOR_ID")) {
              flag = messageBean1.getSender().toLowerCase().compareTo(messageBean2.getSender().toLowerCase());
            }
            if (sortOrder.equalsIgnoreCase("desc")) {
              flag *= -1;
            }
            return flag;
          }
        });

      }
    }
  }

  private boolean filter(String sender, String subject, String isRead, ListSystemMessageForm messgeForm) {

    String searchReadType = messgeForm.getSearchReadType();
    String searchSubject = messgeForm.getSearchSubject();
    String searchSender = messgeForm.getSearchSender();
    boolean isRight = true;

    if (!Utility.isEmpty(searchReadType)) {
      if (!((searchReadType.equals("onlyRead") && isRead.equals("yes")) || (searchReadType.equals("onlyUnread") && isRead.equals("no")))) {
        isRight = false;
      }
    }
    if (!Utility.isEmpty(searchSubject)) {
      if (subject.trim().toLowerCase().indexOf(searchSubject.trim().toLowerCase()) < 0) {
        isRight = false;
      }
    }
    if (!Utility.isEmpty(searchSender)) {
      if (sender.trim().toLowerCase().indexOf(searchSender.trim().toLowerCase()) < 0) {
        isRight = false;
      }
    }
    return isRight;
  }

}